﻿#region Disclaimer/Info
///////////////////////////////////////////////////////////////////////////////////////////////////
// MetaCollection
// 
// MetaCollection is a system to provide a standard structure, permissions and metadata service
// for content organization.
//
// This project is hosted at Google Code at http://code.google.com/p/metacollection/
//
// This project is licensed under the BSD license.  See the License.txt file for more information.
///////////////////////////////////////////////////////////////////////////////////////////////////
#endregion

using System;
using System.Data.SqlClient;
using System.IO;
using System.Data;

namespace MetaCollection.Framework.Helpers
{
	/// <summary>
	/// A special stream wrapper for a blob database column. Binds to the DataReader and disposes/closes it upon dispose.
	/// </summary>
	public class SqlDataReaderStream : Stream, IDisposable
	{
		private SqlCommand m_Command;
		private SqlDataReader m_DataReader;
		private int m_Column;
		private long m_Position;
		private bool m_CanRead;

		/// <summary>
		/// Initializes a new instance of the <see cref="DatabaseStream"/> class.
		/// </summary>
		/// <param name="reader">The reader to use as the data source.</param>
		/// <param name="columnOrdinal">The column ordinal.</param>
		public SqlDataReaderStream(SqlCommand command, int columnOrdinal)
		{
			if (command == null)
				throw new ArgumentNullException("command");
			m_Command = command;
			if (m_Command.Connection.State == ConnectionState.Closed)
				m_Command.Connection.Open();
			m_DataReader = m_Command.ExecuteReader(CommandBehavior.SequentialAccess);
			m_Column = columnOrdinal;
			m_CanRead = m_DataReader.Read();
		}

		/// <summary>
		/// Gets a value indicating whether the current stream supports reading.
		/// </summary>
		/// <value></value>
		/// <returns>true if the stream supports reading; otherwise, false.
		/// </returns>
		public override bool CanRead
		{
			get { return m_DataReader.HasRows && m_CanRead; }
		}

		/// <summary>
		/// A DatabaseStream supports seeking
		/// </summary>
		/// <value></value>
		/// <returns>true if the stream supports seeking; otherwise, false.
		/// </returns>
		public override bool CanSeek
		{
			get { return true; }
		}

		/// <summary>
		/// A DatabaseStream does not support writing.
		/// </summary>
		/// <value></value>
		/// <returns>true if the stream supports writing; otherwise, false.
		/// </returns>
		public override bool CanWrite
		{
			get { return false; }
		}

		/// <summary>
		/// When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device.
		/// </summary>
		/// <exception cref="T:System.IO.IOException">
		/// An I/O error occurs.
		/// </exception>
		public override void Flush()
		{

		}

		public override long Length
		{
			get { throw new InvalidOperationException("Length can not be determined with a forward reader only stream."); }
		}

		/// <summary>
		/// When overridden in a derived class, gets or sets the position within the current stream.
		/// </summary>
		/// <value></value>
		/// <returns>
		/// The current position within the stream.
		/// </returns>
		/// <exception cref="T:System.IO.IOException">
		/// An I/O error occurs.
		/// </exception>
		/// <exception cref="T:System.NotSupportedException">
		/// The stream does not support seeking.
		/// </exception>
		/// <exception cref="T:System.ObjectDisposedException">
		/// Methods were called after the stream was closed.
		/// </exception>
		public override long Position
		{
			get
			{
				return m_Position;
			}
			set
			{
				m_Position = value;
			}
		}

		/// <summary>
		/// When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
		/// </summary>
		/// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between <paramref name="offset"/> and (<paramref name="offset"/> + <paramref name="count"/> - 1) replaced by the bytes read from the current source.</param>
		/// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin storing the data read from the current stream.</param>
		/// <param name="count">The maximum number of bytes to be read from the current stream.</param>
		/// <returns>
		/// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
		/// </returns>
		/// <exception cref="T:System.ArgumentException">
		/// The sum of <paramref name="offset"/> and <paramref name="count"/> is larger than the buffer length.
		/// </exception>
		/// <exception cref="T:System.ArgumentNullException">
		/// 	<paramref name="buffer"/> is null.
		/// </exception>
		/// <exception cref="T:System.ArgumentOutOfRangeException">
		/// 	<paramref name="offset"/> or <paramref name="count"/> is negative.
		/// </exception>
		/// <exception cref="T:System.IO.IOException">
		/// An I/O error occurs.
		/// </exception>
		/// <exception cref="T:System.NotSupportedException">
		/// The stream does not support reading.
		/// </exception>
		/// <exception cref="T:System.ObjectDisposedException">
		/// Methods were called after the stream was closed.
		/// </exception>
		public override int Read(byte[] buffer, int offset, int count)
		{
			if (m_DataReader.IsDBNull(m_Column))
				return 0;
			long read = m_DataReader.GetBytes(m_Column, m_Position, buffer, offset, count);
			m_Position += read; //update our position.
			return (int)read;
		}

		/// <summary>
		/// When overridden in a derived class, sets the position within the current stream.
		/// </summary>
		/// <param name="offset">A byte offset relative to the <paramref name="origin"/> parameter.</param>
		/// <param name="origin">A value of type <see cref="T:System.IO.SeekOrigin"/> indicating the reference point used to obtain the new position.</param>
		/// <returns>
		/// The new position within the current stream.
		/// </returns>
		/// <exception cref="T:System.IO.IOException">
		/// An I/O error occurs.
		/// </exception>
		/// <exception cref="T:System.NotSupportedException">
		/// The stream does not support seeking, such as if the stream is constructed from a pipe or console output.
		/// </exception>
		/// <exception cref="T:System.ObjectDisposedException">
		/// Methods were called after the stream was closed.
		/// </exception>
		public override long Seek(long offset, SeekOrigin origin)
		{
			if (origin == SeekOrigin.Begin)
				m_Position = offset;
			else if (origin == SeekOrigin.Current)
				m_Position += offset;
			else
				throw new NotSupportedException("Seeking from the end of the stream is not supported.");
			return m_Position;
		}

		/// <summary>
		/// Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.
		/// </summary>
		public override void Close()
		{
			base.Close();
			if (!m_DataReader.IsClosed)
			{
				m_DataReader.Close();
			}
			if (m_Command != null && m_Command.Connection.State != System.Data.ConnectionState.Closed)
			{
				m_Command.Connection.Close();
			}
		}

		public override void SetLength(long value)
		{
			throw new NotImplementedException();
		}

		public override void Write(byte[] buffer, int offset, int count)
		{
			throw new NotImplementedException();
		}

		/// <summary>
		/// Releases the unmanaged resources used by the <see cref="T:System.IO.Stream"/> and optionally releases the managed resources.
		/// </summary>
		/// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
		protected override void Dispose(bool disposing)
		{
			base.Dispose(disposing);
			if (disposing)
			{
				if (m_DataReader != null)
				{
					if (!m_DataReader.IsClosed)
						m_DataReader.Close();
					m_DataReader.Dispose();
				}
				if (m_Command != null)
				{
					if (m_Command.Connection.State != System.Data.ConnectionState.Closed)
						m_Command.Connection.Close();
					m_Command.Dispose();
				}
			}
		}
	}

}
